package org.testabilityexplorer.hosted;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.jar.JarFile;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class Analyze extends HttpServlet {

	private File tempFile;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		writer.print("HELLO!");
		writer.flush();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doPost coming in");
		if(ServletFileUpload.isMultipartContent(req)) {
			try {
				uploadJar(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		} else {
			throw new RuntimeException("Expected multipart form, but did not come through");
		}
		JarFile jarFile = new JarFile(tempFile);
		
		ServletOutputStream out = resp.getOutputStream();
		out.print("Thanks!");
		out.flush();
	}

	private void uploadJar(HttpServletRequest req) throws FileUploadException, IOException {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(req);
		for (FileItem file : items) {
			System.out.println(file);
		}
		FileItem file = items.get(0);
		tempFile = File.createTempFile("temp-upload", "");
		FileUtils.writeByteArrayToFile(tempFile, file.get());
	}

	
}
